package com.xianyun.common.security.common.filter;

import com.xianyun.common.core.constant.Constants;
import com.xianyun.common.core.constant.HttpStatus;
import com.xianyun.common.core.domain.Response;
import com.xianyun.common.core.domain.TokenContent;
import com.xianyun.common.core.utils.ServletUtils;
import com.xianyun.common.redis.service.RedisService;
import com.xianyun.common.security.common.TokenUserProperties;
import com.xianyun.common.security.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * @author mac_zyj
 */
@Order(10)
@Slf4j
@WebFilter(filterName="TokenAuthorFilter",urlPatterns = {"/api/*","/blog/*"})
public class TokenAuthorFilter implements Filter {

    @Autowired
    private RedisService redisService;

    @Autowired
    private TokenUserProperties serverUserProperties;

    @Override
    public void destroy() {
        log.info("校验器销毁");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse rep = (HttpServletResponse) response;
        log.info("Head Filter Token 拦截检查");
        //设置允许跨域的配置
        // 这里填写你允许进行跨域的主机ip（正式上线时可以动态配置具体允许的域名和IP）
        rep.setHeader("Access-Control-Allow-Origin", "*");
        // 允许的访问方法
        rep.setHeader("Access-Control-Allow-Methods","POST, GET, PUT, OPTIONS, DELETE, PATCH");
        // Access-Control-Max-Age 用于 CORS 相关配置的缓存
        rep.setHeader("Access-Control-Max-Age", "3600");
        rep.setHeader("Access-Control-Allow-Headers","token,Origin, X-Requested-With, Content-Type, Accept");

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        //header方式
        String token = req.getHeader("token");
        Response<String> resultInfo=new Response<>();
        boolean isFilter = false;
        String method = ((HttpServletRequest) request).getMethod();
        if (Constants.OPTIONS.equals(method)) {
            rep.setStatus(HttpServletResponse.SC_OK);
        }else {
            if (null == token || token.isEmpty()) {
                resultInfo.setCode(HttpStatus.UNAUTHORIZED);
                resultInfo.setMsg("用户授权认证没有通过!客户端请求参数中无token信息");
            } else {
                if (null != getTokenContent(token)) {
                    resultInfo.setCode(2000);
                    resultInfo.setMsg("用户授权认证通过!");
                    isFilter = true;
                } else {
                    resultInfo.setCode(HttpStatus.UNAUTHORIZED);
                    resultInfo.setMsg("用户授权认证没有通过!客户端请求参数token信息无效");
                }
            }
            // 验证失败
            if (resultInfo.getCode() == HttpStatus.UNAUTHORIZED) {
                ServletUtils.getResultToCallBack(rep,resultInfo);
                return;
            }

            if (isFilter) {
                log.info("token filter过滤ok!");
                chain.doFilter(request, response);
            }
        }
    }

    @Override
    public void init(FilterConfig arg) throws ServletException {
        log.info("校验器初始化");
    }

    private TokenContent getTokenContent(String token){
        TokenContent tokenContent = JwtUtil.getTokenSignOut(token,TokenContent.class,serverUserProperties.getJwtSecretKey());
        if (null!=tokenContent){
            Object result=redisService.getCacheObject("Token-UID-"+tokenContent.getUid());
            if (null!=result&&token.equals(result.toString())){
                return tokenContent;
            }
        }
        return null;
    }
}

